package 网络.NIO;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

public class CharsetExample {
    public static void main(String[] args) {
        // 获取 UTF-8 字符集
        Charset charset = Charset.forName("UTF-8");

        // 创建字符缓冲区
        CharBuffer charBuffer = CharBuffer.allocate(1024);
        charBuffer.append("Hello, NIO!");
        charBuffer.flip();

        // 编码为字节缓冲区
        ByteBuffer byteBuffer = charset.encode(charBuffer);
        System.out.println("Encoded bytes: " + new String(byteBuffer.array()));

        // 解码为字符缓冲区
        CharBuffer decodedCharBuffer = charset.decode(byteBuffer);
        System.out.println("Decoded chars: " + decodedCharBuffer.toString());
    }
}
